# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

import json
import pandas as pd
import FetchData

import time
import csv

# API 接口地址
# http://test-openapi.hzxnt.com/v100/{接口名} 测试环境接口地址
# http://openapi.hzxnt.com/v100/{接口名} 生产环境接口地址

base_url = "http://openapi.hzxnt.com/v100/"

token_url           = base_url + "token/apply"
station_list_url    = base_url + "station/list"
pv_data_min_url     = base_url + "station/fetchDataMin/pv"
pv_data_hour_url    = base_url + "station/fetchDataHour/pv"
pv_station_info_url = base_url + "station/overView/pv"

#
# token_url = 'http://test-openapi.hzxnt.com/v100/token/apply'  # 测试环境接口
# projectlist_url = 'http://test-openapi.hzxnt.com/v100/station/list'
# pvdata_min_url = 'http://test-openapi.hzxnt.com/v100/station/fetchDataMin/pv'
# pvdata_hour_url = 'http://test-openapi.hzxnt.com/v100/station/fetchDataHour/pv'

# 请求参数
app_key = 'chenkunqi'
app_secret = 'Ssa7C_JZtvh_CuyZt_pW8jp'

# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # print_hi('PyCharm')

    # 选择使用测试环境或生产环境
    api_token = token_url  # 或 production_api_url

    get_5min_data = True

    data_url = pv_data_hour_url
    if get_5min_data:
        data_url = pv_data_min_url

    # 获取 token
    token = FetchData.fetch_token(api_token, app_key, app_secret)

    if token:
        print(f"获取到的 token：{token}")
    else:
        print("未能成功获取 token，请检查接口地址或参数是否正确。")


    if token:
        # # 获取站点列表
        # data_station_list = FetchData.fetch_project_list(station_list_url, token)
        # if data_station_list:
        #     print(data_station_list)
        # else:
        #     print("未能成功获取 项目列表，请检查接口地址或参数是否正确。")


        station_code = "02500005"
        start_time  = "2023-09-28 00:00:00"
        end_time    = "2025-09-28 00:00:00"
        # start_time  = "2025-04-03 00:00:00"
        # end_time    = "2025-09-28 00:00:00"

        data_list = []
        empty_count = 0
        for i in range(1, 721):
            data_pv = FetchData.fetch_pv_data_list(api_url=data_url,token=token,station_code=station_code,
                                                   start_time=start_time,end_time=end_time,
                                                   prm_page_index=i, prm_page_size=30 )
            print(f"当前第{i}")
            data_list.append(data_pv)
            if (data_pv is None) or len(data_pv) == 0:
                empty_count = empty_count + 1
                if empty_count >= 5:
                    break
            time.sleep(0.1)

        if len(data_list)> 0:  # json 数据转成panda数据
            # for item in data_list:
            #     for j in item:
            #         print(json.dumps(j, indent=4, ensure_ascii=False))
            # # print(data_pv) # [{},{}]

            # 展平数据列表
            flattened_data = [item for sublist in data_list for item in sublist]

            if get_5min_data:
                # 定义可能缺失的字段及其默认值
                default_fields = {
                    'peak_zone': 0,
                    'valley_zone' :0,
                    'og_peak_zone': 0,
                    'og_valley_zone': 0,
                    'nml_zone':0,
                    'og_nml_zone':0
                }

                # 补充缺失的字段
                for item in flattened_data:
                    for field, default_value in default_fields.items():
                        if field not in item:
                            item[field] = default_value

            # 获取所有列名
            keys = flattened_data[0].keys()

            print(keys)

            file_name = f"{station_code}_1hour.csv"
            if get_5min_data:
                file_name = f"{station_code}_5min.csv"

            # 写入 CSV 文件
            with open(file_name, "w", newline="", encoding="utf-8-sig") as csvfile:
                writer = csv.DictWriter(csvfile, fieldnames=keys)
                writer.writeheader()
                writer.writerows(flattened_data)
            print("数据已成功写入 CSV 文件。")


        else:
            print("未能成功获取数据列表，请检查接口地址或参数是否正确。")

# See PyCharm help at https://www.jetbrains.com/help/pycharm/





